//
//  HomeController.m
//  DingDongXiChe
//
//  Created by wtjr on 2018/1/3.
//  Copyright © 2018年 xieyingze. All rights reserved.
//

#import "HomeController.h"
#import "HomeMenuView.h"
#import "HomeLocationView.h"
#import "HomeViewModel.h"
#import "DDPackageController.h"
#import "CustomAnnotationView.h"
#import "CarBrandModel.h"

@interface HomeController ()<AMapLocationManagerDelegate,MAMapViewDelegate>
/**
 地图视图
 */
@property (nonatomic, strong) MAMapView *mapView;
/**
 位置管理器
 */
@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) HomeMenuView *menuView;

@property (nonatomic, strong) HomeLocationView *locationView;

@property (nonatomic, strong) HomeViewModel *viewModel;

@end

@implementation HomeController

#pragma mark - ********************生命周期********************

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.locationManager setLocatingWithReGeocode:YES];
    [self.locationManager startUpdatingLocation];
}

#pragma mark - ********************配置信息********************

- (void)configuration {
    self.navTitle = @"叮咚";
    [self showCustomNavView];
    [self hideLeftBackItem];
    [self.navView setViewShadow:kCOLOR_shadowDark offset:CGSizeMake(0, 3) radius:kUI_ShawRadius];
    
    self.menuView.viewModel = self.viewModel;
    self.locationView.viewModel = self.viewModel;
}

- (void)initSubViews {
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.locationView];
}

- (void)autoLayoutForSubViews {
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0).insets(UIEdgeInsetsMake(64, 0, 0, 0));
    }];
    [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
        make.bottom.equalTo(@-10);
        make.height.equalTo(@100);
    }];
    [self.locationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.menuView);
        make.bottom.equalTo(self.menuView.mas_top).offset(-10);
        make.width.height.equalTo(@30);
    }];
    [self hideAMapViewComponse];
}

- (void)bindViewModel {
    @weakify(self);
    [self.viewModel.updateLocationSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.locationManager startUpdatingLocation];
    }];
    [self.viewModel.updateMenuViewLayoutSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self updateMenuViewLayout:x];
    }];
    [self.viewModel.gotoServiceDetailSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self gotoServiceDetailCtrl:(ServiceModel *)x];
    }];
    [self.viewModel.updateMAPointAnnotationSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self updateMAPointAnnotations:(NSArray *)x];
    }];
}

#pragma mark - ********************基础方法********************

/**
 隐藏地图icon和罗盘组件
 */
- (void)hideAMapViewComponse {
    [self.view layoutIfNeeded];
    for (UIView *view in self.mapView.subviews) {
        if (view.bounds.size.width <= 100) {
            [view removeFromSuperview];
        }
    }
}

#pragma mark - ********************代理方法********************

/**
 定位成功 更新位置
 @param manager <#manager description#>
 @param location <#location description#>
 @param reGeocode <#reGeocode description#>
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    [self.mapView setCenterCoordinate:location.coordinate];
    [self.mapView setZoomLevel:15 animated:YES];

    [self.viewModel.updateCurrentLocationSubject sendNext:reGeocode.formattedAddress];
    [UnityTool setStringValue:[NSString stringWithFormat:@"%@%@",reGeocode.district,reGeocode.street] forKey:kUSER_location];
    self.viewModel.currentCoordiante = location.coordinate;
    [self.viewModel.queryNearbyServiceInfoCommand execute:nil];
}

/**
 重置驻点
 */
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    //取出点标记的标题
    NSString *title = (NSString *)annotation.title;
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        if ([title isEqualToString:@"当前位置"]) {
            static NSString *reuseIndetifier = @"selectedAnnotationReuseIndetifier";
            MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                              reuseIdentifier:reuseIndetifier];
            }
            annotationView.image = [UIView locationImageWithImage:[UIImage imageNamed:@"dd_home_headericon"]];
            annotationView.canShowCallout = YES;
            //设置中心点偏移，使得标注底部中间点成为经纬度对应点
            annotationView.centerOffset = CGPointMake(0, -18);
            return annotationView;
        } else {
            //根据点标记标题取出模型
            if (!title.length) {
                return nil;
            }
            ServiceModel *model = [self.viewModel getAnnotationModelWithTitle:title];
            static NSString *reuseIndetifier = @"annotationReuseIndetifier";
            CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation
                                                              reuseIdentifier:reuseIndetifier];
            }
            annotationView.image = [UIImage imageNamed:@"dd_home_annotationIcon"];
            annotationView.imageUrl = model.service_shopUrl;
            annotationView.model = model;
            // 设置为NO，用以调用自定义的calloutView
            annotationView.canShowCallout = NO;
            // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
            annotationView.centerOffset = CGPointMake(0, -18);
            WeakSelf;
            annotationView.clickCompleted = ^(ServiceModel *md) {
                NSLog(@"%@",md.service_shopUrl);
                [weakself gotoServiceDetailCtrl:md];
            };
            return annotationView;
        }
    }
    return nil;
}


#pragma mark - ********************响应事件********************
/**
 更新底部菜单的布局
 */
- (void)updateMenuViewLayout:(id)x {
    [self.menuView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@([x integerValue] == 0 ? 100 : 300));
    }];
    [UIView animateWithDuration:0.25 animations:^{
       [self.view layoutIfNeeded];
    }];
}
/**
 在地图更新显示周边服务站点
 */
- (void)updateMAPointAnnotations:(NSArray *)arr {
    for (ServiceModel *model in arr) {
        MAPointAnnotation *anno = [MAPointAnnotation new];
        anno.title = model.service_title;
        anno.subtitle = model.service_description;
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake(model.service_latitude, model.service_longitude);
        anno.coordinate = location;
        [_mapView addAnnotation:anno];
    }
}
/**
 跳转到服务套餐
 @param model AnnotationModel
 */
- (void)gotoServiceDetailCtrl:(ServiceModel *)model {
    DDPackageController *ctrl = [DDPackageController new];
    ctrl.model = model;
    [self.navigationController pushViewController:ctrl animated:YES];
}

#pragma mark - ********************懒加载*********************

- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [MAMapView new];
        _mapView.alpha = 0.9;
        _mapView.showsScale = NO;
        _mapView.delegate = self;
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        [_mapView setCustomMapStyle:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/dingdong_style.data", [NSBundle mainBundle].bundlePath]]];
        [_mapView setCustomMapStyleEnabled:YES];
        
        //自定义定位小蓝点
        MAUserLocationRepresentation *representation = [MAUserLocationRepresentation new];
        representation.showsAccuracyRing = NO;
        representation.showsHeadingIndicator = YES;
        representation.fillColor = [kCOLOR_light_blue colorWithAlphaComponent:0.3];;
        representation.lineWidth = 1;
        representation.enablePulseAnnimation = YES;
        representation.image = [UIView locationImageWithImage:[UIImage imageNamed:@"dd_home_headericon"]];
        [_mapView updateUserLocationRepresentation:representation];
    }
    return _mapView;
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [AMapLocationManager new];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 100;
        //禁止系统暂停定位
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
        //允许在后台定位
        [_locationManager setAllowsBackgroundLocationUpdates:YES];
        //设置允许连续定位逆地理
        [self.locationManager setLocatingWithReGeocode:YES];
    }
    return _locationManager;
}

- (HomeMenuView *)menuView {
    if (!_menuView) {
        _menuView = [HomeMenuView new];
    }
    return _menuView;
}

- (HomeLocationView *)locationView {
    if (!_locationView) {
        _locationView = [HomeLocationView new];
    }
    return _locationView;
}

- (HomeViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [HomeViewModel new];
    }
    return _viewModel;
}

@end
